package com.example.lib_base.base.mvp.view;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.lib_base.base.BaseApplication;
import com.example.lib_base.base.mvp.presenter.BasePresenter;
import com.trello.rxlifecycle2.components.support.RxAppCompatDialogFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;


/**
 * @author yedong
 * @date 2019/1/11
 * MVP中V层Fragment基类
 */
public abstract class BaseMvpFragment<V, P extends BasePresenter<V>> extends RxAppCompatDialogFragment {
    public Activity mActivity;
    protected View mRootView;
    protected P mPresenter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(getLayoutId(), container, false);
        mPresenter = createPresenter();
        if (mPresenter != null){
            mPresenter.attachView((V) this);
        }
        return mRootView;
    }

    /**
     * 获取布局Id
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 创建Presenter
     *
     * @return
     */
    protected abstract P createPresenter();

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
        mActivity = getActivity();
        initData();
        initView();
        initEvent();
        loadData();
    }

    /**
     * 初始化数据（接收activity间的传值）
     */
    protected void initData() {

    }

    /**
     * 初始化View
     */
    protected void initView() {

    }

    /**
     * 初始化事件
     */
    protected void initEvent() {

    }

    /**
     * 加载数据
     */
    protected void loadData() {

    }

    /**
     * 通过id控件查找控件
     *
     * @param id
     * @param <T>
     * @return
     */
    public <T extends View> T $(@IdRes int id) {
        return mRootView.findViewById(id);
    }


    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (mPresenter != null) {
            mPresenter.detachView();
        }

        super.onDestroy();
    }

    @Subscribe
    public void eventBusDefault(Object o) {
        // do nothing
    }
}
